package pl.edu.pjwstk.kor.database;

import java.io.File;
import java.net.URL;

import javax.annotation.PostConstruct;

import org.apache.commons.io.FileUtils;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;

public class Db4oDatabase implements Database {
	private final static String DEV_DB_FILE = "src/main/resources/sbql4j/db.db4o";

	private final ObjectContainer connection;
	private final File tmpDatabaseFile;

	public Db4oDatabase() {
		URL u = Db4oDatabase.class.getResource("/sbql4j/db.db4o");
		if(u != null) {
			System.out.println(u.toString());
		} else {
			throw new IllegalStateException("No dtabase file!");
		}
		
		try {
			File dbFile = new File(u.toURI());
			tmpDatabaseFile = File.createTempFile("db4o_", ".db4o");
			FileUtils.copyFile(dbFile, tmpDatabaseFile);
			
			System.out.println("Temporary db file created in: " + tmpDatabaseFile.getAbsolutePath());
			
			this.connection = Db4oEmbedded.openFile(tmpDatabaseFile.getAbsolutePath());
		} catch (Exception e) {
			throw new IllegalStateException("Can not initalize application", e);
		}
	}
	
	Db4oDatabase(boolean developmentMode) {
		if(developmentMode) {
			File dbFile = new File(DEV_DB_FILE);
			this.tmpDatabaseFile = null;
			
			this.connection = Db4oEmbedded.openFile(dbFile.getAbsolutePath());
			
			System.err.println("Database in development mode.");
		} else {
			throw new IllegalStateException("Not in development mode");
		}
	}

	@Override
	public ObjectContainer getObjectContainer() {
		return connection;
	}
	
	@PostConstruct
	public void destory() {
		if(tmpDatabaseFile != null) {
			if(FileUtils.deleteQuietly(tmpDatabaseFile)) {
				System.out.println("Temporary database file deleted");
			} else {
				System.out.println("Unable to delete tmp database file");
			}
		}
	}
}
